var mysql = require('mysql')

// 配置数据库
var mysql = require('mysql');
var pool = mysql.createPool({
    connectionLimit: 10,
    host: 'localhost',
    user: 'root',
    password: 'root',
    database: 'school',
    timezone: "08:00" //从数据库获取的时间日期正常
});

var query = require('../model/query')

/**
 * 根据小组组号获取学生信息
 * @param {小组组号} groupId 
 * @param {*} callback 
 */
function findStudentByGroupId(groupId, callback) {
    let sql = 'select * from `student` where `group`=' + groupId
    console.log(sql)
    query(pool, sql).then(function (ret) {
        console.log(ret)
        callback(null, ret)
    }).catch(function (err) {
        callback(err)
    })
}

/**
 * 更新学生该课题掌握情况
 * @param {课题信息} json 
 * @param {*} callback 
 */
function update(json, callback) {
    console.log(json)
    let sql = 'select * from topic where id=' + json.topicId
    console.log(sql)
    query(pool, sql).then(function (ret) {
        console.log(ret)
        let type = json.type
        if (type == 0) {
            if (ret[0].flunk) {
                json.studentId += ',' + ret[0].flunk
            }
            if (json.studentId[json.studentId.length - 1] == ',') {
                json.studentId = json.studentId.substring(0, json.studentId.length - 1)
            }
            sql = 'UPDATE topic SET flunk = ("' + json.studentId + '") where id = ' + json.topicId
        } else if (type == 1) {
            if (ret[0].good) {
                json.studentId += ',' + ret[0].good
            }
            if (json.studentId[json.studentId.length - 1] == ',') {
                json.studentId = json.studentId.substring(0, json.studentId.length - 1)
            }
            sql = 'UPDATE topic SET good = ("' + json.studentId + '") where id = ' + json.topicId
        } else if (type == 2) {
            if (ret[0].proficient) {
                json.studentId += ',' + ret[0].proficient
            }
            if (json.studentId[json.studentId.length - 1] == ',') {
                json.studentId = json.studentId.substring(0, json.studentId.length - 1)
            }
            sql = 'UPDATE topic SET proficient = ("' + json.studentId + '") where id = ' + json.topicId
        }

        console.log(sql)
        query(pool, sql).then(function (ret) {
            console.log(ret)
            callback(null, 'success')
        }).catch(function (err) {
            callback(err)
        })
    }).catch(function (err) {
        callback(err)
    })
}

function getLastTopic(callback){
    let sql = 'SELECT * FROM topic ORDER BY id DESC LIMIT 1'
    console.log(sql)
    query(pool, sql).then(function (ret) {
        console.log(ret)
        callback(null, ret)
    }).catch(function (err) {
        callback(err)
    })
}

exports.update = update
exports.findStudentByGroupId = findStudentByGroupId
exports.getLastTopic = getLastTopic